export default {
	data() {
		return {
			pickKey: '',
			pickList: [],
			pickMoreKey: '',
			currentTime: this.getCurrentTime(),
			ssq: [],
			autoPlay: true,
		};
	},
	methods: {
		//*****公共区域
		videoPlay(e) {
			this.autoPlay = false;
		},
		videoPause(e) {
			this.autoPlay = true;
		},
		//打开弹出层
		openPopup(key) {
			if (key == undefined) { //默认打开 showPopup
				this.popupObj.showPopup = true;
			} else { //打开指定popup
				this.popupObj[key] = true;
			};
		},
		//关闭弹出
		closePopup() {
			for (let key in this.popupObj) {
				this.popupObj[key] = false;
			};
		},
		//确认弹出层
		confirmPopup() {
			var _this = this;
			for (let key in _this.formDataPopup) {
				var obj = _this.formDataPopup[key]
				if (obj.isMust) {
					switch (obj.type) { //1.字符串 2.布尔值 3.数组
						case 1:
							if (obj.value == "") {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								return;
							};
							if (obj.pattern) {
								if (obj.pattern.test(obj.value) == false) {
									uni.showToast({
										title: obj.patternTitle,
										icon: 'none',
										duration: 2000
									});
									return;
								}
							}
							break;
						case 2:
							if (obj.value == false) {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								return;
							};
							break;
						case 3:
							if (obj.value.length == 0) {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								return;
							};
							break;
					};
				}
			};
			for (let key in this.formDataPopup) {
				this.formDataPopup[key].value = "";
			}
			for (let key in this.popupObj) {
				this.popupObj[key] = false;
			};
			//处理确定后的逻辑
		},
		//打开选择
		openPicker(key) {
			this.pickKey = key;
			this.pickList = this[key];
			this.$refs.picker.open();
			if (this.formData[key].level == 1) { //单层选择
				var index = this.pickList[0].findIndex(item => item.label == this.formData[key].value);
				if (index !== -1) {
					this.$refs.picker.setIndexs([index], true)
				} else {
					this.$refs.picker.setIndexs([0], true)
				};
			} else {
				this.pickMoreKey = this.formData.area.moreKey;
				var index = this.pickList[0].findIndex(item => item.label == this.formData[key].value.split(',')[
					0]);
				var jndex = -1;
				for (let i = 0; i < this[this.pickMoreKey].length; i++) {
					this[this.pickMoreKey][i].forEach((item, i) => {
						if (item.label == this.formData[key].value.split(',')[1]) {
							jndex = i;
						};
					});
				};
				if (index !== -1 && jndex !== -1) {
					setTimeout(() => {
						this.$refs.picker.setColumnValues(1, this[this.pickMoreKey][index]);
						this.$refs.picker.setIndexs([index, jndex], true);
					}, 20)
				} else {
					this.$refs.picker.setIndexs([0, 0], true)
				};
			};
		},
		//拨打电话
		call(tel) {
			if (tel == undefined) {
				console.log(tel)
				uni.makePhoneCall({
					phoneNumber: this.$store.state.tel + ''
				});
			} else {
				console.log(tel)
				uni.makePhoneCall({
					phoneNumber: tel + ''
				});
			};
		},
		//选择发生变化
		changePicker(e, key) {
			if (this.formData[key].level !== 1) { //多层选择
				var {
					columnIndex,
					index
				} = e;
				if (columnIndex === 0) {
					this.$refs.picker.setColumnValues(1, this[this.pickMoreKey][index])
				};
			}
		},
		//确认选择
		confirmPicker(e, key) {
			if (this.formData[key].level == 1) { // 单层
				this.formData[key].value = e.value[0].label;
			} else {
				this.formData[key].value = e.value[0].label + ',' + e.value[1].label;
			};
		},
		//打开时间选择器
		openTimePicker(key) {
			this.pickKey = key;
			if (this.formData[key].value == '') {
				this.currentTime = this.getCurrentTime()
			} else {
				this.currentTime = this.formData[key].value
			}
			this.$refs.timePicker.open();
		},
		//确认时间选择器
		confirmTimePicker(e, key) {
			console.log(e)
			var value = e.value;
			var time = "";
			if (e.mode == 'time') {
				time = value;
			} else {
				time = this.timestampToTime(value);
			};
			this.formData[key].value = time;
			this.formData[key].isShow = false;
		},
		//多选打开
		openCheckPicker(key) {
			this.pickList = this[key][0];
			this.pickKey = key;
			this.formData[key].isShow = true;
		},
		//多选确定
		confirmCheckPicker(e, key) {
			var _this = this;
			if (e.value.length == 0) {
				return;
			}
			var array = e.value;
			var textArr = [];
			array.forEach(item => {
				textArr.push(_this[key][0].find(item1 => item1.value == item).label)
			});
			textArr = textArr.join(',');
			_this.formData[key].value = textArr;
			_this.formData[key].ids = array.join(',');
			_this.formData[key].isShow = false;
		},
		//打开省市区选择
		openSsq(key) {
			this.pickKey = key;
			this.$refs.ssqRef.open();
		},
		//省市区选择发生变化
		changeSsq(e) {
			this.formData[this.pickKey].value = e.join(',');
		},
		//上传图片
		upPhoto(key) {
			var _this = this;
			_this.pickKey = key;
			var count = 0; //总长度
			if (_this.formData[key].photoLength == 1) { //只能上传1张
				count = 1;
			} else { //上传多张
				count = _this.formData[key].photoLength - _this.formData[key].value.length;
			};
			if (_this.formData[key].isCropping) { //需要裁剪
				_this.$refs.cropping.open(); //打开图片裁剪选择器
				if (_this.formData[key].selWidth) {
					_this.$refs.cropping.selWidth = _this.formData[key].selWidth;
				};
				if (_this.formData[key].selHeight) {
					_this.$refs.cropping.selHeight = _this.formData[key].selHeight;
				};
			} else {
				uni.chooseImage({
					count, //当前可上传数量
					async success(res) {
						const tempFilePaths = res.tempFilePaths; // 获取临时路径
						uni.showLoading({
							title: '正在上传...'
						});
						// 正式环境******
						for (let item of tempFilePaths) {
							var bool = await _this.isImageBig(item, 10);
							if (!bool) {
								let res = await Vue.uploadFile('common/upload', item);
								if (_this.formData[_this.pickKey].photoLength == 1) {
									_this.formData[_this.pickKey].value = [res.fullurl];
								} else {
									_this.formData[_this.pickKey].value.push(res.fullurl)
								};
							}
						};
						// 测试环境*****
						// for (let item of tempFilePaths) {
						// 	var bool = await _this.isImageBig(item, 10);
						// 	if (!bool) {
						// 		if (_this.formData[key].photoLength == 1) {
						// 			_this.formData[key].value = [item];
						// 		} else {
						// 			_this.formData[key].value.push(item)
						// 		}
						// 	}
						// };
						uni.hideLoading();
					}
				})
			}
		},
		//判断图片是否大于2MB
		async isImageBig(path, number) {
			var bool = false;
			var size = await new Promise(ok => {
				uni.getFileInfo({
					filePath: path,
					success: function(res) {
						ok(res.size)
					},
					fail: function(err) {
						console.error('获取文件信息失败：', err);
					}
				});
			})
			if (size > (number * 1024 * 1024)) {
				uni.showToast({
					title: "上传文件不能大于" + number + "MB",
					icon: "none"
				})
				bool = true;
				uni.hideLoading();
			};
			return bool
		},
		//删除图片
		removePhoto(key, index) {
			var _this = this;
			_this.formData[key].value.splice(index, 1)
		},
		//预览图片
		lookPhoto(key, index) {
			var _this = this;
			uni.previewImage({
				urls: _this.formData[key].value,
				current: index,
				longPressActions: {
					indicator: 'number',
					loop: true
				}
			});
		},
		// 获取当前时间的方法，返回格式为'YYYY-MM-DD HH:mm:ss'
		getCurrentTime() {
			const now = new Date();
			const year = now.getFullYear();
			const month = (now.getMonth() + 1).toString().padStart(2, '0');
			const day = now.getDate().toString().padStart(2, '0');
			const hours = now.getHours().toString().padStart(2, '0');
			const minutes = now.getMinutes().toString().padStart(2, '0');
			const seconds = now.getSeconds().toString().padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		isLogin() {
			var token = uni.getStorageSync('token');
			if (!token) {
				uni.showModal({
					title: '温馨提示',
					content: '此时此刻需要您登录喔~',
					confirmText: '去登录',
					cancelText: '继续浏览',
					complete(e) {
						if (e.confirm) {
							uni.navigateTo({
								url: "/pages/myPages/login/login"
							});
						}
					}
				});
				return false; // 未登录，返回 false
			}
			return true; // 已登录，返回 true
		},
		//查看图片 单张
		lookUrl(url) {
			uni.previewImage({
				urls: [url],
				current: 0,
				showmenu: true
			})
		},
		//查看图片 多张
		lookUrls(urlList, index) {
			uni.previewImage({
				urls: urlList,
				current: index,
				showmenu: true
			})
		},
		//获取当前位置 并返回对象
		getLocation() {
			var _this = this;
			uni.getLocation({
				type: 'gcj02',
				success: async function(res) {
					uni.request({
						url: "https://apis.map.qq.com/ws/geocoder/v1/?key=CDVBZ-F7YRS-NXZOW-6ZIC5-7YV6Q-2EF4A&location=" +
							res.latitude + ',' + res.longitude,
						success(res) {
							var obj = {
								province: res.data.result.address_component
									.province,
								city: res.data.result.address_component.city,
								district: res.data.result.address_component
									.district,
								address: res.data.result.address,
								latitude: res.data.result.location.lat,
								longitude: res.data.result.location.lng,
							};
							_this.$store.commit('setLocation', obj);
						}
					});
				}
			});
		},
		//选择指定位置 并返回对象
		chooseLocation() {
			var _this = this;
			uni.chooseLocation({
				success: async function(res) {
					if (res.longitude == undefined) {
						uni.showToast({
							title: "未成功选取到地址",
							icon: "none"
						});
						return;
					};
					uni.request({
						url: "https://apis.map.qq.com/ws/geocoder/v1/?key=CDVBZ-F7YRS-NXZOW-6ZIC5-7YV6Q-2EF4A&location=" +
							res.latitude + ',' + res.longitude,
						success(res) {
							var obj = {
								province: res.data.result.address_component
									.province,
								city: res.data.result.address_component.city,
								district: res.data.result.address_component
									.district,
								address: res.data.result.address,
								latitude: res.data.result.location.lat,
								longitude: res.data.result.location.lng,
							};
							_this.$store.commit('setLocation', obj);
						}
					})
				}
			});
		},
		//打开导航
		openLocation(latitude, longitude) {
			uni.openLocation({
				latitude: latitude * 1,
				longitude: longitude * 1,
				success: function() {
					console.log('success');
				}
			});
		},
		//保存本地图片
		saveImage(url) {
			uni.saveImageToPhotosAlbum({
				filePath: url,
				success: function(res) {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					})
				}
			});
		},
		//提交表单
		async onSubmit() {
			var _this = this;
			//表单验证
			for (let key in _this.formData) {
				var obj = _this.formData[key]
				if (obj.isMust) {
					switch (obj.type) { //1.字符串 2.布尔值 3.数组
						case 1:
							if (obj.value == "") {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								return;
							};
							if (obj.pattern) {
								if (obj.pattern.test(obj.value) == false) {
									uni.showToast({
										title: obj.patternTitle,
										icon: 'none',
										duration: 2000
									});
									return;
								}
							}
							break;
						case 2:
							if (obj.value == false) {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								return;
							};
							break;
						case 3:
							if (obj.value.length == 0) {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								return;
							};
							break;
					};
				}
			};
			//表单验证后的逻辑
			var data = {
				// nickname: this.formData.nickname.value
			};
			uni.showLoading({
				title: "提交中...",
				mask: true
			});
			// let res = await $post('apply/coach_apply', data);
			uni.hideLoading();
			uni.showModal({
				title: '提交成功',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						uni.navigateBack()
					}
				}
			});
		},
		getToday() {
			const today = new Date();
			const year = today.getFullYear();
			const month = String(today.getMonth() + 1).padStart(2, '0');
			const day = String(today.getDate()).padStart(2, '0');
			const formattedDate = `${year}-${month}-${day}`;
			return formattedDate;
		},
		getTomorrow() {
			const today = new Date();
			const tomorrow = new Date(today);
			tomorrow.setDate(today.getDate() + 1);
			const year = tomorrow.getFullYear();
			const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
			const day = String(tomorrow.getDate()).padStart(2, '0');
			const formattedDate = `${year}-${month}-${day}`;
			return formattedDate;
		},
		toTime(timestamp) {
			// 如果时间戳是秒级，转换为毫秒级
			if (timestamp.toString().length === 10) {
				timestamp *= 1000;
			}

			// 创建 Date 对象
			const date = new Date(timestamp);

			// 获取年、月、日、时、分、秒
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1
			const day = date.getDate().toString().padStart(2, '0');
			const hours = date.getHours().toString().padStart(2, '0');
			const minutes = date.getMinutes().toString().padStart(2, '0');
			const seconds = date.getSeconds().toString().padStart(2, '0');

			// 拼接成需要的格式
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		//时间戳转换成时间
		timestampToTime(timestamp) {
			var date = new Date(timestamp);
			var Y = date.getFullYear();
			var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);
			var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
			var h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours());
			var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
			var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			var time = Y + M + D + h + m + s;
			switch (this.formData[this.pickKey].mode) {
				case 'datetime':
					time = Y + '-' +
						M + '-' + D + ' ' + h + ':' + m + ':' + s;
					break;
				case 'date':
					time = Y + '-' + M + '-' + D;
					break;
				case 'time':
					time = h + ':' + m;
					break;
				case 'year-month':
					time = Y + '-' + M;
					break;
				case 'year':
					time = Y;
					break;
			}
			return time;
		},
		toTamp(timestamp) {
			// 如果时间戳是秒级，转换为毫秒级
			if (timestamp.toString().length === 10) {
				timestamp *= 1000;
			}

			// 创建 Date 对象
			const date = new Date(timestamp);

			// 获取年、月、日、时、分、秒
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1
			const day = date.getDate().toString().padStart(2, '0');
			const hours = date.getHours().toString().padStart(2, '0');
			const minutes = date.getMinutes().toString().padStart(2, '0');
			const seconds = date.getSeconds().toString().padStart(2, '0');

			// 拼接成需要的格式
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		changeDate(str) {
			var t;
			switch (arguments.length) {
				case 1:
					t = new Date();
					break;
				case 2:
					if (Object.prototype.toString.call(arguments[1]) === '[object Date]') {
						t = arguments[1];
					} else if (typeof arguments[1] === 'number' && arguments[1].toString().length > 10) {
						t = new Date(arguments[1]);
					} else if (arguments[1] >= 0) {
						t = new Date(parseInt(arguments[1] + '000'));
					} else if (arguments[1] < 0) {
						t = Math.abs(arguments[1]);
						var d = parseInt(t / 60 / 60 / 24);
						var H = parseInt(t / 60 / 60 % 24);
						var i = parseInt(t / 60 % 60);
						var s = parseInt(t % 60);
						str = str.replace(/d([^dHis]*)/g, d > 0 ? d + '$1' : '');
						str = str.replace(/H([^dHis]*)/g, H > 0 ? H + '$1' : d > 0 ? '0' : '');
						str = str.replace(/i([^dHis]*)/g, i > 0 ? i + '$1' : d > 0 || H > 0 ? '0' : '');
						str = str.replace(/s([^dHis]*)/g, s > 0 ? s + '$1' : d > 0 || H > 0 || i > 0 ? '0' : '');
						return str;
					} else {
						return '';
					}
					break;
			}
			var Y = t.getFullYear();
			var y = t.getFullYear().toString().substr(2);
			var M = t.getMonth() + 1;
			var D = t.getDate();
			var H = t.getHours();
			var I = t.getMinutes();
			var S = t.getSeconds();
			if (M < 10) M = '0' + M;
			if (D < 10) D = '0' + D;
			if (H < 10) H = '0' + H;
			if (I < 10) I = '0' + I;
			if (S < 10) S = '0' + S;
			str = str.replace(/Y/g, Y);
			str = str.replace(/y/g, y);
			str = str.replace(/M/g, M);
			str = str.replace(/D/g, D);
			str = str.replace(/H/g, H);
			str = str.replace(/I/g, I);
			str = str.replace(/S/g, S);
			return str;
		},
		//比较两个日期的差值
		getDaysDifference(dateString1, dateString2) {
			// 将日期字符串转换为日期对象
			const date1 = new Date(dateString1);
			const date2 = new Date(dateString2);

			// 计算时间戳差值
			const differenceInTime = Math.abs(date2.getTime() - date1.getTime());

			// 将时间戳差值转换为天数
			const differenceInDays = Math.ceil(differenceInTime / (1000 * 60 * 60 * 24));

			return differenceInDays;
		},
		addDay(dateStr, days) {
			// 将日期字符串转换为 Date 对象
			const date = new Date(dateStr);

			// 获取当前时间戳
			const timestamp = date.getTime();

			// 计算新的时间戳（加上指定的天数）
			const newTimestamp = timestamp + (days * 24 * 60 * 60 * 1000);

			// 创建新的 Date 对象
			const newDate = new Date(newTimestamp);

			// 格式化日期为 YYYY-MM-DD
			const year = newDate.getFullYear();
			const month = String(newDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
			const day = String(newDate.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		yanZheng() {
			var bool = false;
			for (let key in this.formData) {
				var obj = this.formData[key]
				if (obj.isMust) {
					switch (obj.type) { //1.字符串 2.布尔值 3.数组
						case 1:
							if (obj.value == "") {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								bool = true;
								return bool
							};
							if (obj.pattern) {
								if (obj.pattern.test(obj.value) == false) {
									uni.showToast({
										title: obj.patternTitle,
										icon: 'none',
										duration: 2000
									});
									bool = true;
									return bool
								}
							}
							break;
						case 2:
							if (obj.value == false) {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								bool = true;
								return bool
							};
							break;
						case 3:
							if (obj.value.length == 0) {
								uni.showToast({
									title: obj.title,
									icon: 'none',
									duration: 2000
								});
								bool = true;
								return bool
							};
							break;
					};
				}
			}
			return bool;
		}

	}
};